<template>
  <div class="tp" v-loading="state.loading">
    <Header />

    <Content>
      <div class="cp">
        <div class="card">
          <div class="c-title" v-if="state.stepIndex === 0"> 库存校正</div>
          <div v-else-if="state.stepIndex === 1">
            <a-flex gap="middle" align="center">
              <div>校正预览</div>
              <div>
                <a-alert
                  type="warning"
                  show-icon
                  message="注：校正后，系统库存将更新为表格里的盘点数量，请谨慎点击！"
                />
              </div>
            </a-flex>
          </div>

          <div class="line"></div>

          <div class="c-body">
            <div class="steps-container" v-show="state.stepIndex === 0">
              <a-steps :current="state.stepIndex" :items="state.stepList" class="steps" />
            </div>

            <div v-show="state.stepIndex === 0">
              <div class="row-1">
                <a-flex gap="middle" align="center" @mousemove.stop="state.accept = '.xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'">
                  <div>上传Excel</div>
                  <Attachment
                    title="选择文件..."
                    :uploadUrl="`${URL('/product/checkExcelUpload', null, true)}`"
                    :accept="state.accept"
                    :multiple="false"
                    name="stockFile"
                    :maxCount="1"
                    :data="state.uploadData"
                    :showUploadList="true"
                    @change-loading="onChangeLoading"
                  />
                </a-flex>

                <div style="margin-top: 24px">
                  <a-flex align="center" justify="center" gap="middle">
                    <a-button @click="router.back()"> 取消</a-button>

                    <a-button type="primary" @click="onStartPre">提交</a-button>
                  </a-flex>
                </div>
              </div>

              <div class="memo">
                <div class="title">注：</div>
                <div class="item">1.库存校正用于线下Excel库存盘点时，差异库存数量的校正</div>
                <div class="item">2.Excel直接使用下载的Excel上传即可</div>
                <div class="item"
                  >3.Excel里需要填写实际库存数量才能进行校正，否则系统会不处理该条数据
                </div>
                <div class="item">
                  4.如果盘点时发现有库存商品在下载的Excel表格里没有，可以手动添加正确的商品编码，以及实际商品数量进行校正
                </div>
              </div>
            </div>

            <div v-show="state.stepIndex === 1">
              <div class="c-box">
                <a-checkbox v-model:checked="state.isDifferent"> 仅展示有差异库存商品</a-checkbox>
              </div>
              <BasicTable
                @register="registerTable"
                :dataSource="state.dataSource"
                :resizeHeightOffset="140"
                style="margin: 0 -2px"
              />
            </div>
          </div>
        </div>
      </div>
    </Content>

    <Footer v-if="state.stepIndex === 1">
      <a-flex align="center" justify="center" gap="middle" class="f-body">
        <a-button @click="router.back()"> 取消</a-button>

        <a-popconfirm
          title="您确定要执行校正吗"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onSubmit"
        >
          <a-button type="primary">确定校正</a-button>
        </a-popconfirm>
      </a-flex>
    </Footer>
  </div>
</template>

<script setup>
  import { defineOptions, h, reactive, watch } from 'vue';

  import { BasicTable, useTable } from '@/components/Table';

  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import { appendArg, PAGE, POST, URL } from '@/api/http';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useRouter } from 'vue-router';
  import ProImgCell from '@/widget/pro-img-cell.vue';
  import Footer from '@/widget/footer.vue';
  import Attachment from '@/widget/attachment.vue';
  import { getUserName } from '@/utils/auth';

  defineOptions({ name: 'StockCheck' });

  const router = useRouter();

  const { createMessage } = useMessage();

  const uploadData = () => ({ ...appendArg(), opBy: getUserName() });

  const state = reactive({
    accept:'.xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel',
    loading: false,
    uploadData,
    uploadMsg: null,
    stockCheckCode: null,

    isDifferent: false,

    stepIndex: 0,
    stepList: [
      {
        title: '上传Excel',
      },
      {
        title: '校正预览',
      },
    ],
  });

  watch(
    () => [state.stepIndex, state.isDifferent],
    () => {
      const { stepIndex } = state;
      if (stepIndex === 1) {
        reload();
      }
    },
    { immediate: true },
  );

  function onStartPre() {
    const { uploadMsg, stockCheckCode } = state;

    if (uploadMsg) {
      return createMessage.error(uploadMsg);
    }

    if (stockCheckCode) {
      state.stepIndex = 1;
      return;
    }

    return createMessage.error('请上传Excel文件');
  }

  const [registerTable, { reload }] = useTable({
    api: PAGE('/product/getCheckPreviewList'),
    beforeFetch: (arg) => {
      const { stockCheckCode, isDifferent } = state;
      return Object.assign(arg, { stockCheckCode: stockCheckCode || '-1', isDifferent });
    },
    columns: [
      {
        title: '商品名称',
        dataIndex: 'goodsName',
        ellipsis: false,
        width: 290,
        customRender: ({ value: title, record }) =>
          h(ProImgCell, { src: record.goodsImage, title }),
      },
      {
        title: '规格',
        dataIndex: 'specs',
        ellipsis: false,
      },

      {
        title: '库存数量',
        dataIndex: 'num',
        ellipsis: false,
        customRender: ({ value, record }) => `${value || '0'}${record.saleUnit || ''}`,
      },

      {
        title: '盘点数量',
        dataIndex: 'numNew',
        ellipsis: false,
        customRender: ({ value, record }) => `${value || '0'}${record.saleUnit || ''}`,
      },

      {
        title: '差异数量',
        dataIndex: 'numDifference',
        ellipsis: false,
        customRender: ({ value, record }) => {
          let { saleUnit, isProfit } = record;
          saleUnit ||= '';
          value ||= 0;

          return h(
            'span',
            { style: { color: isProfit === 0 ? '#F4432C' : '#747474' } },
            value === 0 ? '-' : `${value}${saleUnit}`,
          );
        },
      },
    ],
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
  });

  async function onSubmit() {
    const { stockCheckCode } = state;

    await POST('/product/checkConfirm', { stockCheckCode });
    createMessage.success('已完成校正');
    await router.back();
  }

  function onChangeLoading(flag, msg, file) {
    state.loading = flag;

    state.uploadMsg = null;
    state.stockCheckCode = null;

    if (msg === 'success') {
      state.stockCheckCode = file.response?.result;
      createMessage.success('文件已上传');
    } else {
      state.uploadMsg = msg;
    }
  }
</script>
<style lang="less" scoped>
  .card {
    margin-bottom: 24px;
    padding: 12px;

    .c-title {
      color: #333;
      font-size: 14px;
      font-weight: 500;
    }

    .line {
      margin: 0 -12px;
      padding-bottom: 8px;
      border-bottom: 1px solid #f0f0f0;
    }

    .c-body {
      padding: 8px 12px;
    }

    :deep(.ant-alert) {
      padding: 2px 6px;
    }
  }

  .steps-container {
    display: flex;
    justify-content: center;
    margin: 24px 0;

    .steps {
      width: 460px;
    }
  }

  .row-1,
  .memo {
    margin: 0 220px;
  }

  .row-1 {
    padding: 32px 0;
  }

  .memo {
    padding: 12px;
    border-radius: 4px;
    background: #fbfbfb;
    color: #666;

    .title {
      padding: 6px 0;
      font-size: 14px;
      font-weight: 500;
    }

    .item {
      padding: 6px 0;
      font-size: 13px;
    }
  }

  .c-box {
    padding: 12px 0;
  }
</style>
